import fs from 'fs'
import path from 'path'

export function readConfigFile<T = any>(filePath: string, names: string[]) {
  if (!fs.existsSync(filePath)) {
    throw new Error(`${filePath} not found`)
  }

  let readPath = ''

  if (fs.statSync(filePath).isDirectory()) {
    for (let i = 0; i < names.length; i++) {
      const file = path.join(filePath, names[i])
      if (fs.existsSync(file)) {
        readPath = file
        break
      }
    }
    if (!readPath) {
      throw new Error(
        `Config file not found in ${filePath}. Possible filenames: ${names.join(', ')}.`
      )
    }
  } else {
    readPath = filePath
  }

  const data = require(readPath) as T

  return { data, readPath }
}
